package com.example.smsquiz;

import java.io.UnsupportedEncodingException;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;

public class SmsClient extends BroadcastReceiver{

	@Override
	public void onReceive(Context context, Intent intent) {

        if (!AppModel.getInstance().isServiceActive()){
            return;
        }

		System.out.println("SMS received");
		Bundle bundle = intent.getExtras();
		Object[] messageObjects = (Object[])bundle.get("pdus");
				
		String messageText = null;
		try {
			messageText = new String(new byte[0], "UTF-8");
		} catch (UnsupportedEncodingException e) {
			AppLogger.WriteError(e);
			e.printStackTrace();
		}
		String address = null;
		for(int i = 0; i < messageObjects.length; i++){
			SmsMessage message = SmsMessage.createFromPdu((byte[]) messageObjects[i]);
			messageText += message.getDisplayMessageBody();
			if(address == null){
				address = message.getDisplayOriginatingAddress();
			}			
		}
		
		SmsDTO smsMessage = new SmsDTO(address, messageText);
		System.out.println("SMS added");
		AppLogger.Write("SMS added");
		AppLogger.Write("From: " + address);
		AppLogger.Write("Text: " + messageText);
		AppModel.getInstance().addMessage(smsMessage);
	}
}
